package com.game;

// C:\Program Files\Eclipse\android-sdk-windows-1.5_r3\tools

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;


public class GaismaView extends SurfaceView implements SurfaceHolder.Callback {

	private GaismaThread mThread;
	private Context mContext;
	private SurfaceHolder mHolder;
	
	/**
	 * Creates the SurfaceView, stores the Context and a SurfaceHolder
	 * 
	 * @param context Is the one with global information about the application
	 * @param attrs
	 */
	public GaismaView(Context context, AttributeSet attrs)
	{		
		super(context, attrs);
		Log.i("GAISMA LOG:: ",this.getClass().getName()+"::Constructor" );
		
		mContext = context;
		
		mHolder = getHolder();
		mHolder.addCallback(this);	
		
		// So it can receive touches
		setFocusable(true);		
	}
	
	
	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
	{
		
	}
	
	
	/* (non-Javadoc)
	 * The thread is started when the surface is completely created, hence this function.
	 * 
	 * @see android.view.SurfaceHolder.Callback#surfaceCreated(android.view.SurfaceHolder)
	 */
	public void surfaceCreated(SurfaceHolder holder)
	{
		Log.i("GAISMA LOG:: ",this.getClass().getName()+"::surfaceCreated" );
		if(!mThread.isAlive())
		{
			Log.i("GAISMA LOG:: ",this.getClass().getName()+"::startingThread" );
			mThread.setmRunning(true);
			mThread.start();
		}
		
	}
	
	
	/* (non-Javadoc)
	 * Called when the surface is destroyed, and the application is about to end.
	 * It stops the thread.
	 * 
	 * @see android.view.SurfaceHolder.Callback#surfaceDestroyed(android.view.SurfaceHolder)
	 */
	public void surfaceDestroyed(SurfaceHolder holder)
	{
		Log.i("GAISMA LOG:: ",this.getClass().getName()+"::surfaceDestroyed" );
		boolean retry = true;
		mThread.setmRunning(false);
		while(retry)
		{
			try
			{
				mThread.join();
				retry = false;
			}
			catch(InterruptedException e)
			{}
		}
		
	}
	
	
	/* (non-Javadoc)
	 * Gets input and notifies the thread.
	 * 
	 * @see android.view.View#onTouchEvent(android.view.MotionEvent)
	 */
	public boolean onTouchEvent(MotionEvent event) 
	{
		if(event.getAction() == MotionEvent.ACTION_DOWN) return mThread.handleTouch(event);
		else return false;
	}

	
	
	public void setmThread(GaismaThread mThread) {
		this.mThread = mThread;
	}

	public GaismaThread getmThread() {
		return mThread;
	}
	
}
